package com.gui.juc.pool;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.core.util.RandomUtil;
import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Slf4j
public class ThreadPoolDemo2 {

    public static void main(String[] args) {
        ThreadFactory factory = ThreadFactoryBuilder.create().setNamePrefix("gui-task-").build();
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                3,
                3,
                2000,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(100),
                factory,
                new ThreadPoolExecutor.AbortPolicy());

        Future<String> future = threadPool.submit(new CalcTask(false));
        threadPool.shutdown();
        while (!threadPool.isTerminated()) {
            log.warn("让我康康线程执行完了没有");
            Sleeper.sleep(2);
        }
        try {
            String result = future.get();
            log.debug("任务执行成功:{}", result);
        }catch (Exception e) {
            log.error("任务执行失败", e);
        }
        log.debug("任务执行完成！");
    }

    private static class CalcTask implements Callable<String> {
        private boolean errorFlag;

        public CalcTask(boolean errorFlag) {
            this.errorFlag = errorFlag;
        }


        @Override
        public String call() throws Exception {
            Sleeper.sleep(TimeUnit.SECONDS, 1);
            String result = RandomUtil.randomString(6);
            if (errorFlag) {
                int a = 9 / 0;
            }
            log.debug("计算结果为：{}", result);
            return result;
        }
    }


    private static class CalcTask1 implements Runnable {

        private boolean errorFlag;

        public CalcTask1(boolean errorFlag) {
            this.errorFlag = errorFlag;
        }

        @Override
        public void run() {
            Sleeper.sleep(TimeUnit.SECONDS, 1);
            String result = RandomUtil.randomString(6);
            if (errorFlag) {
                int a = 9 / 0;
            }
            log.debug("计算结果为：{}", result);
        }
    }
}
